<template>
  <div class="achievement-report-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-select
              v-model="yearFilter"
              placeholder="评价年份"
              clearable
              @change="handleSearch"
              style="width: 200px"
            >
              <el-option
                v-for="year in years"
                :key="year"
                :label="year"
                :value="year"
              />
            </el-select>
            
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
          
          <el-button
            type="success"
            :icon="Download"
            @click="handleExport"
            :loading="exporting"
          >
            导出Excel
          </el-button>
        </div>
      </template>

      <!-- 达成度趋势图 -->
      <div class="chart-container">
        <div ref="trendChartRef" style="width: 100%; height: 400px"></div>
      </div>

      <!-- 达成度表格 -->
      <el-table
        v-loading="loading"
        :data="achievements"
        border
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="indicatorName" label="指标点名称" width="120" />
        <el-table-column prop="directEvaluation" label="直接评价" width="120">
          <template #default="{ row }">
            {{ (row.directEvaluation * 100).toFixed(1) }}%
          </template>
        </el-table-column>
        <el-table-column prop="graduateSelfEval" label="自评" width="120">
          <template #default="{ row }">
            {{ (row.graduateSelfEval * 100).toFixed(1) }}%
          </template>
        </el-table-column>
        <el-table-column prop="internshipEval" label="实习评价" width="120">
          <template #default="{ row }">
            {{ (row.internshipEval * 100).toFixed(1) }}%
          </template>
        </el-table-column>
        <el-table-column prop="teacherEval" label="教师评价" width="120">
          <template #default="{ row }">
            {{ (row.teacherEval * 100).toFixed(1) }}%
          </template>
        </el-table-column>
        <el-table-column prop="comprehensiveScore" label="综合评价值" width="120">
          <template #default="{ row }">
            {{ (row.comprehensiveScore * 100).toFixed(1) }}%
          </template>
        </el-table-column>
        <el-table-column prop="isAchieved" label="是否达成" width="120">
          <template #default="{ row }">
            <el-tag :type="row.isAchieved ? 'success' : 'danger'">
              {{ row.isAchieved ? '已达成' : '未达成' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="evaluationYear" label="评价年份" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import request from '../api/request'

const loading = ref(false)
const exporting = ref(false)
const yearFilter = ref('')
const achievements = ref([])
const years = ref([])
const trendChartRef = ref(null)
let trendChart = null

// 获取毕业要求达成度数据
const fetchAchievements = async () => {
  try {
    loading.value = true
    const res = await request.get('/api/graduation-requirement-achievements', {
      params: {
        evaluationYear: yearFilter.value
      }
    })
    achievements.value = res.data || []
    updateTrendChart()
  } catch (error) {
    console.error('获取达成度数据失败:', error)
    ElMessage.error('获取达成度数据失败')
  } finally {
    loading.value = false
  }
}

// 获取年份列表
const fetchYears = async () => {
  try {
    const res = await request.get('/api/graduation-requirement-achievements/years')
    years.value = res.data
  } catch (error) {
    console.error('获取年份列表失败:', error)
  }
}

// 更新趋势图
const updateTrendChart = () => {
  if (!trendChartRef.value) return

  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value)
  }

  // 按年份分组数据
  const yearGroups = {}
  achievements.value.forEach(item => {
    if (!yearGroups[item.evaluationYear]) {
      yearGroups[item.evaluationYear] = []
    }
    yearGroups[item.evaluationYear].push(item)
  })

  // 计算每年的平均值
  const years = Object.keys(yearGroups).sort()
  const directEvalData = []
  const selfEvalData = []
  const internshipEvalData = []
  const teacherEvalData = []
  const comprehensiveData = []

  years.forEach(year => {
    const yearData = yearGroups[year]
    const avg = (arr) => (arr.reduce((sum, item) => sum + item, 0) / arr.length * 100).toFixed(1)
    
    directEvalData.push(avg(yearData.map(item => item.directEvaluation)))
    selfEvalData.push(avg(yearData.map(item => item.graduateSelfEval)))
    internshipEvalData.push(avg(yearData.map(item => item.internshipEval)))
    teacherEvalData.push(avg(yearData.map(item => item.teacherEval)))
    comprehensiveData.push(avg(yearData.map(item => item.comprehensiveScore)))
  })

  const option = {
    title: {
      text: '毕业要求达成度趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['直接评价', '自评', '实习评价', '教师评价', '综合评价值']
    },
    xAxis: {
      type: 'category',
      data: years
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: '直接评价',
        type: 'line',
        data: directEvalData
      },
      {
        name: '自评',
        type: 'line',
        data: selfEvalData
      },
      {
        name: '实习评价',
        type: 'line',
        data: internshipEvalData
      },
      {
        name: '教师评价',
        type: 'line',
        data: teacherEvalData
      },
      {
        name: '综合评价值',
        type: 'line',
        data: comprehensiveData
      }
    ]
  }

  trendChart.setOption(option)
}

// 导出Excel
const handleExport = async () => {
  try {
    exporting.value = true
    const res = await request.get('/api/graduation-requirement-achievements/export', {
      params: {
        evaluationYear: yearFilter.value
      },
      responseType: 'blob'
    })
    
    console.log('收到的响应对象类型:', typeof res);
    console.log('收到的响应对象 instanceof Blob:', res instanceof Blob);
    console.log('收到的响应对象:', res);

    if (!(res instanceof Blob)) {
      console.error('错误：后端响应数据不是Blob类型，无法导出！', res);
      ElMessage.error('导出失败：响应数据格式不正确。');
      return; // 提前退出，避免后续错误
    }

    const url = window.URL.createObjectURL(res)
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `毕业要求达成度报表_${yearFilter.value || '全部'}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exporting.value = false
  }
}

const handleSearch = () => {
  fetchAchievements()
}

const resetSearch = () => {
  yearFilter.value = ''
  fetchAchievements()
}

const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString()
}

onMounted(async () => {
  await fetchYears()
  await fetchAchievements()
  window.addEventListener('resize', () => {
    trendChart?.resize()
  })
})

onUnmounted(() => {
  trendChart?.dispose()
  window.removeEventListener('resize', () => {
    trendChart?.resize()
  })
})
</script>

<style scoped>
.achievement-report-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  gap: 10px;
}

.chart-container {
  margin: 20px 0;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 